<template>
  <div class="home">
    <div style="margin: 10px 0; font-size: 18px; font-weight: bold">
      密码修改
    </div>

    <el-form
      ref="changeForm"
      class="form"
      :model="changeForm"
      :rules="changeRules"
      label-position="left"
      label-width="180px"
    >
      <el-form-item label="旧密码" prop="oldPasswd">
        <el-input v-model="changeForm.oldPasswd" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPasswd">
        <el-input v-model="changeForm.newPasswd" show-password />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="goBack()">取 消</el-button>
      <el-button type="primary" @click="changePsw()">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { updatePasswd } from '@/api/user'
import md5 from 'js-md5'
export default {
  components: {},
  data() {
    return {
      authType: '',
      userInfo: {},
      changeForm: {
        newPasswd: '',
        oldPasswd: ''
      },
      changeRules: {
        newPasswd: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        oldPasswd: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.authType = sessionStorage.getItem('authType')
    this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  },
  methods: {
    changePsw() {
      var pwdRegex = new RegExp(
        '(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{7,30}'
      )

      const type =
        this.authType === 'root' || this.authType === 'nomalAuth' ? '1' : 2
      this.$refs['changeForm'].validate((valid) => {
        if (valid) {
          if (!pwdRegex.test(this.changeForm.newPasswd)) {
            this.$message.warning(
              '您的密码复杂度太低（密码中必须包含字母、数字、特殊字符），请及时修改密码！'
            )
            return
          }
          const param = {
            oldPasswd: md5(this.changeForm.oldPasswd),
            newPasswd: md5(this.changeForm.newPasswd),
            type: type,
            username: this.userInfo.username
              ? this.userInfo.username
              : this.userInfo.staffCode
          }
          updatePasswd(param).then((res) => {
            if (res.code === '0') {
              this.$message({
                message: '修改成功，请重新登录',
                type: 'success'
              })
              this.$store.dispatch('user/logout')
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            }
          })
        }
      })
    },
    goBack() {
      this.$router.back()
    }
  }
}
</script>

<style scoped>
.home {
  margin: 20px;
}

.form {
  width: 50%;
}
</style>
